#include "bsp_lcd.h"
#include "driver/ili9320.h"
#include "stm32f2xx_ll_gpio.h"

volatile uint16_t *m_bsp_lcd_cmd = (volatile uint16_t *)(0x6c000000);
volatile uint16_t *m_bsp_lcd_ram = (volatile uint16_t *)(0x6c000002);

ili9320_desc_t m_ili9320;

static void bsp_lcd_io_init() {
  // PG8 LCD BL
  LL_GPIO_InitTypeDef init;

  /* enable the pin */
  LL_GPIO_StructInit(&init);

  init.Pin        = LL_GPIO_PIN_8;
  init.Mode       = LL_GPIO_MODE_OUTPUT;
  init.OutputType = LL_GPIO_OUTPUT_PUSHPULL;

  LL_GPIO_Init(GPIOG, &init);

  LL_GPIO_SetOutputPin(GPIOG, LL_GPIO_PIN_8);
}

static void bsp_lcd_write_cmd(uint8_t reg) { *m_bsp_lcd_cmd = reg; }

static void bsp_lcd_write_data(uint16_t val) { *m_bsp_lcd_ram = val; }
static void bsp_lcd_write_data_block(uint16_t *pdata, uint32_t length) {
  for (uint32_t i = 0; i < length; i++) {
    *m_bsp_lcd_ram = *pdata++;
  }
}
static uint16_t bsp_lcd_read_data() { return (*m_bsp_lcd_ram); }

int bsp_lcd_init() {
  bsp_lcd_io_init();
  m_ili9320.read_data   = bsp_lcd_read_data;
  m_ili9320.write_data  = bsp_lcd_write_data;
  m_ili9320.write_cmd   = bsp_lcd_write_cmd;
  m_ili9320.write_block = bsp_lcd_write_data_block;

  return 0;
}
